package com.zj.printdemo;


import com.inuker.bluetooth.library.BluetoothClient;


import android.content.Context;
import android.content.Intent;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import android.util.Log;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;

import cn.hlife.com.bluetooth20_connect.lib.BluetoothService;
import cn.hlife.com.bluetooth20_connect.lib.PrintPic;
import cn.hlife.com.bluetooth20_connect.util.LogUtils;

import static android.content.ContentValues.TAG;


public class PrintDemo extends Activity {
    Button btnSearch;
    Button btnSendDraw;
    Button btnSend, printImage;
    Button btnClose;
    EditText edtContext;
    EditText edtPrint;
    private static final int REQUEST_ENABLE_BT = 2;
    BluetoothService mService = null;
    BluetoothDevice con_dev = null;
    private static final int REQUEST_CONNECT_DEVICE = 1;  //获取设备消息
//	BluetoothClient mClient;


    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mService = new BluetoothService(this, mHandler);

        //蓝牙不可用退出程序
        if (mService.isAvailable() == false) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //蓝牙未打开，打开蓝牙

        if (mService.isBTopen() == false) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        }
        try {
            btnSendDraw = (Button) this.findViewById(R.id.btn_test);
            btnSendDraw.setOnClickListener(new ClickEvent());
            btnSearch = (Button) this.findViewById(R.id.btnSearch);
            btnSearch.setOnClickListener(new ClickEvent());
            btnSend = (Button) this.findViewById(R.id.btnSend);
            btnSend.setOnClickListener(new ClickEvent());
            btnClose = (Button) this.findViewById(R.id.btnClose);
            btnClose.setOnClickListener(new ClickEvent());
            printImage = (Button) this.findViewById(R.id.print_image);
            printImage.setOnClickListener(new ClickEvent());
            edtContext = (EditText) findViewById(R.id.txt_content);
            findViewById(R.id.button).setOnClickListener(new ClickEvent());
            btnClose.setEnabled(false);
            btnSend.setEnabled(false);
            btnSendDraw.setEnabled(false);
        } catch (Exception ex) {
            Log.e("出错信息", ex.getMessage());
        }
//		mClient= new BluetoothClient(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mService != null)
            mService.stop();
        mService = null;
    }

    class ClickEvent implements View.OnClickListener {
        public void onClick(View v) {
            if (v.getId() == R.id.button) {
//                Q();
                a();
//                b();
            } else if (v == btnSearch) {
                Intent serverIntent = new Intent(PrintDemo.this, DeviceListActivity.class);      //运行另外一个类的活动
                startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
            } else if (v == btnSend) {
                String msg = edtContext.getText().toString();
                if (msg.length() > 0) {
                    mService.sendMessage(msg + "\n", "GBK");
                }
            } else if (v == btnClose) {
                mService.stop();
            } else if (v == btnSendDraw) {
                String msg = "";
                byte[] cmd = new byte[3];
                cmd[0] = 0x1b;
                cmd[1] = 0x21;
//					cmd[2] |= 0x10;
//					mService.write(cmd);           //倍宽、倍高模式
//					mService.sendMessage("恭喜您！\n", "GBK");
                cmd[2] &= 0xEF;
                mService.write(cmd);//取消倍高、倍宽模式
                //初始化指令
//                byte[] bytes = new byte[2];
//                bytes[0] = 0x1b;
//                bytes[1] = 0x40;
//                mService.write(bytes);
//                cmd[0] = 0x1C;
//                cmd[1] = 0x49;
//                cmd[2] = 1;//设置 90 °旋转
                try {
                    mService.write(cmd);
                    byte[] byte1 = new byte[6];

                    byte1[0] = 0x1B;
                    byte1[1] = 0x44;
                    byte1[2] = 2;//距第1列1个字符间距
                    byte1[3] = 9;//距第1列7个字符间距
                    byte1[4] = 14;//距第1列15个字符间距
                    byte1[5] = 0; //结束
                    mService.write(byte1);
                    msg = "测试1 ";
                    mService.write(msg.getBytes("GBK"));
                    msg = "测试2 ";
                    mService.write(msg.getBytes("GBK"));
                    msg = "测试3 ";
                    mService.write(msg.getBytes("GBK"));
                    mService.write(new byte[]{0x0d});
                    mService.write("1234567890123456\r".getBytes());

//                msg = "测试 ";
//                mService.sendMessage(msg, "GBK");
//                msg = "这是测试数据\n\n\n\n";
//                mService.sendMessage(msg, "GBK");

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else if (v == printImage) {
                printImage();
            }
        }
    }

    /**
     * 创建一个Handler实例，用于接收BluetoothService类返回回来的消息
     */
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BluetoothService.MESSAGE_STATE_CHANGE:
                    switch (msg.arg1) {
                        case BluetoothService.STATE_CONNECTED:   //已连接
                            Toast.makeText(getApplicationContext(), "Connect successful",
                                    Toast.LENGTH_SHORT).show();
                            btnClose.setEnabled(true);
                            btnSend.setEnabled(true);
                            btnSendDraw.setEnabled(true);
                            break;
                        case BluetoothService.STATE_CONNECTING:  //正在连接
                            LogUtils.e("蓝牙调试 正在连接.....");
                            break;
                        case BluetoothService.STATE_LISTEN:     //监听连接的到来
                        case BluetoothService.STATE_NONE:
                            LogUtils.e("蓝牙调试 等待连接.....");
                            break;
                    }
                    break;
                case BluetoothService.MESSAGE_CONNECTION_LOST:    //蓝牙已断开连接
                    Toast.makeText(getApplicationContext(), "Device connection was lost",
                            Toast.LENGTH_SHORT).show();
                    btnClose.setEnabled(false);
                    btnSend.setEnabled(false);
                    btnSendDraw.setEnabled(false);
                    break;
                case BluetoothService.MESSAGE_UNABLE_CONNECT:     //无法连接设备
                    LogUtils.e("无法连接设备....");
                    Toast.makeText(PrintDemo.this, "Unable to connect device",
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }

    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_ENABLE_BT:      //请求打开蓝牙
                if (resultCode == Activity.RESULT_OK) {   //蓝牙已经打开
                    Toast.makeText(this, "Bluetooth open successful", Toast.LENGTH_LONG).show();
                } else {                 //用户不允许打开蓝牙
                    finish();
                }
                break;
            case REQUEST_CONNECT_DEVICE:     //请求连接某一蓝牙设备
                if (resultCode == Activity.RESULT_OK) {   //已点击搜索列表中的某个设备项
                    String address = data.getExtras()
                            .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);  //获取列表项中设备的mac地址
                    con_dev = mService.getDevByMac(address);
                    if (con_dev != null) {
                        mService.connect(con_dev);
                    } else {
                        Toast.makeText(getApplicationContext(), "没有找到该设备",
                                Toast.LENGTH_SHORT).show();
                    }
                }
                break;
        }
    }

    //打印图形
    @SuppressLint("SdCardPath")
    private void printImage() {
        byte[] sendData = null;
        PrintPic pg = new PrintPic();
        pg.initCanvas(384);
        pg.initPaint();
        pg.drawImage(0, 0, "/mnt/sdcard/icon.jpg");
        sendData = pg.printDraw();
        mService.write(sendData);   //打印byte流数据
    }

    //关机
    public void Q() {
        try {

            //获得ServiceManager类
            Class<?> ServiceManager = Class
                    .forName("android.os.ServiceManager");

            //获得ServiceManager的getService方法
            Method getService = ServiceManager.getMethod("getService", java.lang.String.class);

            //调用getService获取RemoteService
            Object oRemoteService = getService.invoke(null, Context.POWER_SERVICE);

            //获得IPowerManager.Stub类
            Class<?> cStub = Class
                    .forName("android.os.IPowerManager$Stub");
            //获得asInterface方法
            Method asInterface = cStub.getMethod("asInterface", android.os.IBinder.class);
            //调用asInterface方法获取IPowerManager对象
            Object oIPowerManager = asInterface.invoke(null, oRemoteService);
            //获得shutdown()方法
            Method shutdown = oIPowerManager.getClass().getMethod("shutdown", boolean.class, boolean.class);
            //调用shutdown()方法
            shutdown.invoke(oIPowerManager, false, true);

        } catch (Exception e) {
            Log.e(TAG, e.toString(), e);
        }
    }

    public void a() {
        Intent intent = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
        intent.putExtra("android.intent.extra.KEY_CONFIRM", false);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

    }

    public void b() {
        try {
            Runtime.getRuntime().exec("su -c \"/system/bin/shutdown\"");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
